const appReader = require('node-app-reader');
const Path = require('path');
const Fs = require('fs-extra');
const hasha = require('hasha');
const { spiders, apps } = require('../model/index');
const { categories } = require('./commonData');

module.exports = async (category) => {
    const items = await spiders.find({ status: true });
    for (let i = 0, len = items.length; i < len; i++) {
        try {
            const item = items[i];
            const apkPath = Path.join(__dirname, '../uploads', item.apkPath);
            let { name, id: package, version: vername, versionCode: vercode } = await appReader(apkPath);

            if (Array.isArray(package)) {
                package = package[0];
            }

            await spiders.updateOne({ url: item.url }, { status: false });

            const data = {
                icon: item.icon,
                md5hash: await hasha.fromFile(apkPath, { algorithm: 'md5' }),
                name: name || item.name,
                package,
                size: Fs.statSync(apkPath).size,
                vername,
                vercode,
                apkPath: item.apkPath,
                sshots: item.banners,
                category: item.category, // 分类id
                dlLink: item.dlLink,
            };

            await apps.updateOne({ package }, data, { upsert: true });
            await Fs.remove(apkPath);
        } catch (err) {
            console.error(err);
        }
    }
    console.log('-> ', categories.find(el => el.id === category).name, '解包完成');
}